import { readdir, stat } from 'fs/promises';
import { unstable_noStore as noStore } from 'next/cache';
import { join } from 'path';
import type { Stats } from 'node:fs';
import { FileItem } from '@/registry/types';

// 获取镜像列表
export async function fetchMirrors(slug: string[]): Promise<FileItem[]> {
    try {
        noStore();
        //文件根目录
        const rootPath = join(process.cwd(), process.env.FILE_LOCATION || '/');
        const filePath = join(rootPath, ...slug);
        const files = await readdir(filePath);
        // 这个data数组中装的是当前文件夹下所有的文件名(包括文件夹)
        return await Promise.all(
            files.map(async function (file) {
                // 加上父级访问更深层的文件夹
                const dataFile: Stats = await stat(`${filePath}/` + file);
                return {
                    type: dataFile.isDirectory() ? 'dir' : 'file',
                    filepath: dataFile.isDirectory() ? join('/', ...slug, file) : join(process.env.FILE_LOCATION || '/', ...slug, file),
                    filename: file,
                    birthtime: dataFile.birthtime.toLocaleString(),
                    mtime: dataFile.mtime.toLocaleString(),
                    size: dataFile.size,
                };
            })
        );
    } catch (error) {
        return [];
    }
}
